using Microsoft.Extensions.Logging;
using OrchardCore.Data.EFCore;
using OrchardCore.Environment.Shell;
using OrchardCore.Modules;
using OrchardCore.Data;
using OrchardCore.Environment.Shell.Removing;

namespace OrchardCore.Data.EFCore;

/// <summary>
/// EF Core自动迁移处理器
/// 在租户激活时自动应用EF Core迁移
/// </summary>
public class EFCoreAutomaticMigrations : IModularTenantEvents
{
    private readonly IEFCoreDataMigrationManager _migrationManager;
    private readonly ILogger<EFCoreAutomaticMigrations> _logger;

    public EFCoreAutomaticMigrations(
        IEFCoreDataMigrationManager migrationManager,
        ILogger<EFCoreAutomaticMigrations> logger)
    {
        _migrationManager = migrationManager;
        _logger = logger;
    }

    public Task ActivatingAsync() => Task.CompletedTask;
    public Task ActivatedAsync() => Task.CompletedTask;
    public Task TerminatingAsync() => Task.CompletedTask;
    public Task TerminatedAsync() => Task.CompletedTask;
    public Task RemovingAsync(ShellRemovingContext context) => Task.CompletedTask;

    // 兼容旧的带参数方法（可选，实际可删除）
    public Task ActivatedAsync(ShellSettings shellSettings)
    {
        _logger.LogInformation("Tenant '{TenantName}' activated, checking for EF Core migrations", shellSettings.Name);
        return Task.CompletedTask;
    }

    public async Task ActivatingAsync(ShellSettings shellSettings)
    {
        try
        {
            _logger.LogInformation("Applying EF Core migrations for tenant: {TenantName}", shellSettings.Name);
            var contextTypes = GetDbContextTypes();
            foreach (var contextType in contextTypes)
            {
                try
                {
                    var count = await _migrationManager.ApplyMigrationsAsync(contextType);
                    if (count > 0)
                    {
                        _logger.LogInformation("Applied {Count} migrations for {ContextType} in tenant: {TenantName}",
                            count, contextType.Name, shellSettings.Name);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Failed to apply migrations for {ContextType} in tenant: {TenantName}",
                        contextType.Name, shellSettings.Name);
                    throw;
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to apply EF Core migrations for tenant: {TenantName}", shellSettings.Name);
            throw;
        }
    }

    public Task DeactivatingAsync(ShellSettings shellSettings)
    {
        _logger.LogInformation("Tenant '{TenantName}' deactivating", shellSettings.Name);
        return Task.CompletedTask;
    }

    public Task DeactivatedAsync(ShellSettings shellSettings)
    {
        _logger.LogInformation("Tenant '{TenantName}' deactivated", shellSettings.Name);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 获取DbContext类型列表
    /// </summary>
    /// <returns>DbContext类型列表</returns>
    private static IEnumerable<Type> GetDbContextTypes()
    {
        return Enumerable.Empty<Type>();
    }
} 